package com.xls.pet.mapper;

import com.mybatisflex.core.BaseMapper;
import com.xls.pet.entity.Category;
import com.xls.pet.entity.Item;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 分类 映射层。
 *
 * @author xls
 * @since 2024-06-21
 */
public interface CategoryMapper extends BaseMapper<Category> {

    @Select("""
            WITH RECURSIVE CategoryHierarchy AS (
                SELECT id, parent_id
                FROM category
                WHERE id = #{id}
                UNION ALL
                SELECT c.id, c.parent_id
                FROM category c
                JOIN CategoryHierarchy ch ON c.parent_id = ch.id
            )
            SELECT id
            FROM CategoryHierarchy ch
            """)
    List<Integer> getchildCategoryIdList(@Param("id") Integer id);

    default void setCategoryName(List<Category> categoryList, Item item) {
        item.setCategoryName(getCategoryNameById(categoryList, item.getCategoryId()));
    }

    private String getCategoryNameById(List<Category> categoryList, Integer categoryId) {
        List<Category> categoryParentList = new ArrayList<>();
        Category currentCategory = categoryList.stream()
                .filter(category -> Objects.equals(category.getId(), categoryId)).findFirst().orElse(new Category());
        getParentCategory(categoryParentList, categoryList, currentCategory);
        return categoryParentList.stream()
                .sorted(Comparator.comparing(Category::getId))
                .map(Category::getName)
                .collect(Collectors.joining("/"));
    }

    private void getParentCategory(List<Category> categoryParentList, List<Category> categoryList, Category currentCategory) {
        categoryParentList.add(currentCategory);
        categoryList.stream()
                .filter(category -> Objects.equals(category.getId(), currentCategory.getParentId())).findFirst()
                .ifPresent(parentCategory -> getParentCategory(categoryParentList, categoryList, parentCategory));
    }

}
